import axios from 'axios';

const API_URL = 'http://localhost:8080/api';

// 设置axios拦截器，添加token到请求头
export const setupAxiosInterceptors = (token: string) => {
  axios.interceptors.request.use(
    (config) => {
      // Skip adding token for login requests
      if (config.url && !config.url.includes('/auth/login')) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );
};

// 初始化axios拦截器 - 在应用启动时调用
export const initializeAuth = () => {
  const token = localStorage.getItem('token');
  if (token) {
    setupAxiosInterceptors(token);
  }
};

interface LoginParams {
  username: string;
  password: string;
  captcha?: string;
  rememberMe?: boolean;
}

interface LoginResponse {
  code: number;
  message: string;
  data: {
    userInfo: {
      userId: number;
      username: string;
      password: string;
      realName: string;
      nickname: string | null;
      avatar: string | null;
      email: string;
      mobile: string;
      gender: number;
      deptId: number | null;
      position: string | null;
      isAdmin: number;
      status: number;
      loginIp: string | null;
      loginDate: string | null;
      creator: string | null;
      createTime: string;
      updater: string | null;
      updateTime: string | null;
      isDeleted: number;
    }
  };
  token: string;
  timestamp: number;
}

export const login = async (params: LoginParams): Promise<LoginResponse> => {
  const response = await axios.post(`${API_URL}/auth/login`, params);
  return response.data;
};

export const logout = () => {
  localStorage.removeItem('userInfo');
  localStorage.removeItem('token');
  window.location.href = '/login';
};

export const getUserInfo = () => {
  const userInfoStr = localStorage.getItem('userInfo');
  return userInfoStr ? JSON.parse(userInfoStr) : null;
};

export const getToken = () => {
  return localStorage.getItem('token');
};

export const isAuthenticated = () => {
  return !!localStorage.getItem('token');
}; 